//
//  ZSPankPay.m
//  悦管家
//
//  Created by apple on 16/7/4.
//
//

#import "ZSPankPay.h"

@implementation ZSPankPay

//插件初始化方法
- (void)pluginInitialize{
    NSLog(@"begin");
    _testUrl=[NSString string];
//    NSArray* URLTypes = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleURLTypes"];
//    if (URLTypes != nil) {
//        NSDictionary* dict = [URLTypes objectAtIndex:0];
//        if (dict != nil) {
//            NSArray* URLSchemes = [dict objectForKey:@"CFBundleURLSchemes"];
//            if (URLSchemes != nil) {
//                self.UrlScheme = [URLSchemes objectAtIndex:0];
//            }
//        }
//    }
}
- (void)echo:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;
    NSString* echo = [command.arguments objectAtIndex:0];
    
    if (echo != nil && [echo length] > 0) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
    } else {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    }
    
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

- (void)pay:(CDVInvokedUrlCommand*)command{

    _testUrl = [command.arguments objectAtIndex:0];

//    NSString * urlStr = [_testUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    if([urlStr hasPrefix:@"%22"] && [urlStr hasSuffix:@"%22"])
//    {
//        urlStr=[urlStr substringWithRange:NSMakeRange(3, urlStr.length-6)];
//    }
//    NSLog(@"The testurl is ----->%@******urlStr----->%@",_testUrl,urlStr);

//    调用控件方法
    [self initWithUIAndUrl:_testUrl];
    
    if (command.arguments ==nil || [command.arguments count]<1) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"参数错误"] callbackId:command.callbackId];
        return;
    }
    if ([command.arguments count]>=2) {//如果传入第二个参数，则使用这个参数作为urlscheme
//        self.UrlScheme = [command.arguments objectAtIndex:1];
    }
    
    NSString* charge = [command.arguments objectAtIndex:0];
    self.CallbackId = command.callbackId;
    
    
    [self.commandDelegate runInBackground:^{
        NSLog(@"charge:'%@'",charge);
        

    }];
    
}
#pragma mark UIAlertViewDelegate
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0)//退出
    {
        if (_payState==0 || _payState==1)
        {
            self.isBack=YES;
            [self.navView removeFromSuperview];
            [self.webviews removeFromSuperview];
            [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:_testUrl] callbackId:self.CallbackId];
            [_secKeyboard hideKeyboard];
        }
        if (_payState==2)
        {
            [self.webviews goBack];
            self.isBack=YES;
            [self.webviews removeFromSuperview];
            [self.navView removeFromSuperview];
            [_secKeyboard hideKeyboard];
        }
    }else //不退出
    {
        self.isBack=NO;
    }
}

#pragma mark  初始化UI控件

-(void) initWithUIAndUrl:(NSString *)url
{
    _current_page_title = [NSString string];
    
    self.webviews = [[UIWebView alloc] initWithFrame:CGRectMake(0, 70, self.viewController.view.frame.size.width, self.viewController.view.frame.size.height-70)];
    self.webviews.delegate=self;
    
#if  0
    //    这个方法是通过这个可以插入js
    [self.webview stringByEvaluatingJavaScriptFromString:testUrl];
    //  可变URL  改用POST 请求  提高安全性
    NSMutableURLRequest * mrequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [mrequest setHTTPMethod:@"POST"];
    [self.webview loadRequest:(NSMutableURLRequest *)mrequest];
    
#endif
    
    [self.webviews loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    [self.webviews setUserInteractionEnabled:YES];
    [self.webviews setScalesPageToFit:YES];
    [self.viewController.view addSubview:self.webviews];
    
    self.navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.viewController.view.frame.size.width, 60)];
    self.navView.backgroundColor =[UIColor colorWithRed:30.0f/255.0f green:144.0f/255.0f blue:255.0f/255.0f alpha:1];
    [self.viewController.view addSubview:self.navView];
    
    self.backBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.backBtn.frame=CGRectMake(10, 20, 35, 35);
    [self.backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backAct:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:self.backBtn];
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.viewController.view.frame.size.width/2-80, 10, 160, 50)];
    self.titleLabel.text=@"招商银行一网通支付";
    self.titleLabel.font = [UIFont systemFontOfSize:16];
    self.titleLabel.textColor=[UIColor whiteColor];
    [self.navView addSubview:self.titleLabel];
    
}

#pragma mark 返回事件处理
-(void) backAct:(id) sender
{
    if ([_current_page_title isEqualToString:@"招商银行一网通支付"]) {
        _payState = 2;
    }
    NSString * msg = @"是否退出";
    if (_payState==0) {
        msg=@"支付成功,确认退出支付吗";
    }
    if (_payState==1) {
        msg=@"支付失败,确认退出支付吗";
    }
    if (_payState==2) {
        msg=@"支付未完成,确认退出支付吗";
    }
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"不退出", nil];
    [alert show];
    
}


#pragma mark 这是webview的代理方法
-(void) webViewDidFinishLoad:(UIWebView *)webView
{

    //获取当前页面的title
    _current_page_title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    if ([_current_page_title isEqualToString:@"悦管家"] || _current_page_title==nil || [_current_page_title isEqualToString:@""])
    {
        [self.navView removeFromSuperview];
        
        [self.webviews removeFromSuperview];
        
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:_testUrl] callbackId:self.CallbackId];
        
        [_secKeyboard hideKeyboard];
    }else{
        self.viewController.title = _current_page_title;
        self.titleLabel.text=_current_page_title;
    }
    
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"WebView加载有问题----%@",[error localizedDescription]);
}

//当嵌入H5页面的时候回进这进行判断

static BOOL FROM = FALSE;
-(BOOL)webView:(UIWebView*)_webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"The URl is ----> %@",request.URL.query);
    if ([request.URL.query rangeOfString:@"MB_EUserP_PayError"].location != NSNotFound && request.URL.query != nil)
    {
        _payState=1;
    }
    if ([request.URL.query rangeOfString:@"MB_EUserP_PayOK"].location != NSNotFound && request.URL.query != nil)
    {
        _payState=0;
    }else {
        _payState=2;
    }
    
    if ([request.URL.host isCaseInsensitiveEqualToString:@"cmbls"]) {
        _secKeyboard = [CMBWebKeyboard shareInstance];
        [_secKeyboard showKeyboardWithRequest:request];
        _secKeyboard.webView = _webView;

        UITapGestureRecognizer* myTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        [self.viewController.view addGestureRecognizer:myTap]; //这个可以加到任何控件上,比如你只想响应WebView，我正好填满整个屏幕
        myTap.delegate = self;
        myTap.cancelsTouchesInView = NO;
        return NO;
    }
   
    return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

-(void)handleSingleTap:(UITapGestureRecognizer *)sender
{
    CGPoint gesturePoint = [sender locationInView:self.webviews];
    
    [_secKeyboard hideKeyboard];
    
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    if (FROM) {
        
        return;
    }
}
- (void)dealloc
{
    [[CMBWebKeyboard shareInstance] hideKeyboard];
}


@end
